#include "user_session_service.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// 创建会话
int create_session(sqlite3 *db, UserSession *session) {
    sqlite3_stmt *stmt = NULL;
    const char *sql = "INSERT INTO user_session (user_id, connection_id, device_info, ip_address, created_at, last_active) "
                      "VALUES (?, ?, ?, ?, datetime(?, 'unixepoch'), datetime(?, 'unixepoch'));";
    
    int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
        return DB_ERROR;
    }
    
    // 绑定参数
    sqlite3_bind_int64(stmt, 1, session->user_id);
    sqlite3_bind_text(stmt, 2, session->connection_id, -1, SQLITE_STATIC);
    
    // 处理可为 NULL 的字段
    if (session->device_info) {
        sqlite3_bind_text(stmt, 3, session->device_info, -1, SQLITE_STATIC);
    } else {
        sqlite3_bind_null(stmt, 3);
    }
    
    if (session->ip_address) {
        sqlite3_bind_text(stmt, 4, session->ip_address, -1, SQLITE_STATIC);
    } else {
        sqlite3_bind_null(stmt, 4);
    }
    
    sqlite3_bind_int64(stmt, 5, session->created_at);
    sqlite3_bind_int64(stmt, 6, session->last_active);
    
    // 执行插入
    rc = sqlite3_step(stmt);
    if (rc != SQLITE_DONE) {
        fprintf(stderr, "Insert failed: %s\n", sqlite3_errmsg(db));
        sqlite3_finalize(stmt);
        return DB_ERROR;
    }
    
    // 获取新生成的ID
    session->id = sqlite3_last_insert_rowid(db);
    
    sqlite3_finalize(stmt);
    return DB_SUCCESS;
}

int update_connection_id_by_user_id(sqlite3 *db, long user_id, const char *new_connection_id) {
    sqlite3_stmt *stmt = NULL;
    const char *sql = "UPDATE user_session SET connection_id = ? WHERE user_id = ?;";
    
    int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
        return DB_ERROR;
    }
    
    // 绑定参数
    sqlite3_bind_text(stmt, 1, new_connection_id, -1, SQLITE_STATIC);
    sqlite3_bind_int64(stmt, 2, user_id);
    
    // 执行更新
    rc = sqlite3_step(stmt);
    if (rc != SQLITE_DONE) {
        fprintf(stderr, "Update connection_id failed: %s\n", sqlite3_errmsg(db));
        sqlite3_finalize(stmt);
        return DB_ERROR;
    }
    
    int rows_affected = sqlite3_changes(db);
    sqlite3_finalize(stmt);
    
    return (rows_affected > 0) ? DB_SUCCESS : DB_ERROR;
}

UserSession** get_sessions_by_user_id(sqlite3 *db, long user_id, int *count) {
    sqlite3_stmt *stmt = NULL;
    const char *sql = "SELECT id, user_id, connection_id, device_info, ip_address, "
                      "strftime('%s', created_at), strftime('%s', last_active) "
                      "FROM user_session WHERE user_id = ?;";
    
    int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
        *count = 0;
        return NULL;
    }
    
    sqlite3_bind_int64(stmt, 1, user_id);
    
    // 第一遍：获取结果数量
    *count = 0;
    while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
        (*count)++;
    }
    
    if (*count == 0) {
        sqlite3_finalize(stmt);
        return NULL;
    }
    
    // 重置语句
    sqlite3_reset(stmt);
    
    // 分配内存
    UserSession **sessions = malloc(*count * sizeof(UserSession*));
    if (!sessions) {
        sqlite3_finalize(stmt);
        *count = 0;
        return NULL;
    }
    
    // 第二遍：获取数据
    int index = 0;
    while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
        UserSession *session = malloc(sizeof(UserSession));
        if (!session) {
            // 内存分配失败，清理已分配的资源
            for (int i = 0; i < index; i++) {
                free_session(sessions[i]);
            }
            free(sessions);
            sqlite3_finalize(stmt);
            *count = 0;
            return NULL;
        }
        
        session->id = sqlite3_column_int64(stmt, 0);
        session->user_id = sqlite3_column_int64(stmt, 1);
        
        // 复制 connection_id
        const char *conn_id = (const char*)sqlite3_column_text(stmt, 2);
        strncpy(session->connection_id, conn_id, sizeof(session->connection_id) - 1);
        session->connection_id[sizeof(session->connection_id) - 1] = '\0';
        
        // 处理可能为 NULL 的字段
        if (sqlite3_column_type(stmt, 3) != SQLITE_NULL) {
            const char *dev_info = (const char*)sqlite3_column_text(stmt, 3);
            session->device_info = strdup(dev_info);
        } else {
            session->device_info = NULL;
        }
        
        if (sqlite3_column_type(stmt, 4) != SQLITE_NULL) {
            const char *ip = (const char*)sqlite3_column_text(stmt, 4);
            session->ip_address = strdup(ip);
        } else {
            session->ip_address = NULL;
        }
        
        session->created_at = sqlite3_column_int64(stmt, 5);
        session->last_active = sqlite3_column_int64(stmt, 6);
        
        sessions[index++] = session;
    }
    
    sqlite3_finalize(stmt);
    return sessions;
}

int delete_sessions_by_user_id(sqlite3 *db, long user_id) {
    sqlite3_stmt *stmt = NULL;
    const char *sql = "DELETE FROM user_session WHERE user_id = ?;";
    
    int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
        return DB_ERROR;
    }
    
    sqlite3_bind_int64(stmt, 1, user_id);
    
    rc = sqlite3_step(stmt);
    if (rc != SQLITE_DONE) {
        fprintf(stderr, "Delete sessions failed: %s\n", sqlite3_errmsg(db));
        sqlite3_finalize(stmt);
        return DB_ERROR;
    }
    
    int rows_affected = sqlite3_changes(db);
    sqlite3_finalize(stmt);
    
    return (rows_affected > 0) ? DB_SUCCESS : DB_ERROR;
}

// 根据ID获取会话
UserSession* get_session_by_id(sqlite3 *db, long session_id) {
    sqlite3_stmt *stmt = NULL;
    const char *sql = "SELECT id, user_id, connection_id, device_info, ip_address, "
                      "strftime('%s', created_at), strftime('%s', last_active) "
                      "FROM user_session WHERE id = ?;";
    
    int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
        return NULL;
    }
    
    sqlite3_bind_int64(stmt, 1, session_id);
    
    rc = sqlite3_step(stmt);
    if (rc != SQLITE_ROW) {
        sqlite3_finalize(stmt);
        return NULL;
    }
    
    // 分配内存并填充数据
    UserSession *session = malloc(sizeof(UserSession));
    if (!session) {
        sqlite3_finalize(stmt);
        return NULL;
    }
    
    session->id = sqlite3_column_int64(stmt, 0);
    session->user_id = sqlite3_column_int64(stmt, 1);
    
    // 复制 connection_id
    const char *conn_id = (const char*)sqlite3_column_text(stmt, 2);
    strncpy(session->connection_id, conn_id, sizeof(session->connection_id) - 1);
    session->connection_id[sizeof(session->connection_id) - 1] = '\0';
    
    // 处理可能为 NULL 的字段
    if (sqlite3_column_type(stmt, 3) != SQLITE_NULL) {
        const char *dev_info = (const char*)sqlite3_column_text(stmt, 3);
        session->device_info = strdup(dev_info);
    } else {
        session->device_info = NULL;
    }
    
    if (sqlite3_column_type(stmt, 4) != SQLITE_NULL) {
        const char *ip = (const char*)sqlite3_column_text(stmt, 4);
        session->ip_address = strdup(ip);
    } else {
        session->ip_address = NULL;
    }
    
    session->created_at = sqlite3_column_int64(stmt, 5);
    session->last_active = sqlite3_column_int64(stmt, 6);
    
    sqlite3_finalize(stmt);
    return session;
}

// 根据连接ID获取会话
UserSession* get_session_by_connection_id(sqlite3 *db, const char *connection_id) {
    sqlite3_stmt *stmt = NULL;
    const char *sql = "SELECT id, user_id, connection_id, device_info, ip_address, "
                      "strftime('%s', created_at), strftime('%s', last_active) "
                      "FROM user_session WHERE connection_id = ?;";
    
    int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
        return NULL;
    }
    
    sqlite3_bind_text(stmt, 1, connection_id, -1, SQLITE_STATIC);
    
    rc = sqlite3_step(stmt);
    if (rc != SQLITE_ROW) {
        sqlite3_finalize(stmt);
        return NULL;
    }
    
    // 分配内存并填充数据
    UserSession *session = malloc(sizeof(UserSession));
    if (!session) {
        sqlite3_finalize(stmt);
        return NULL;
    }
    
    session->id = sqlite3_column_int64(stmt, 0);
    session->user_id = sqlite3_column_int64(stmt, 1);
    
    // 复制 connection_id
    const char *conn_id = (const char*)sqlite3_column_text(stmt, 2);
    strncpy(session->connection_id, conn_id, sizeof(session->connection_id) - 1);
    session->connection_id[sizeof(session->connection_id) - 1] = '\0';
    
    // 处理可能为 NULL 的字段
    if (sqlite3_column_type(stmt, 3) != SQLITE_NULL) {
        const char *dev_info = (const char*)sqlite3_column_text(stmt, 3);
        session->device_info = strdup(dev_info);
    } else {
        session->device_info = NULL;
    }
    
    if (sqlite3_column_type(stmt, 4) != SQLITE_NULL) {
        const char *ip = (const char*)sqlite3_column_text(stmt, 4);
        session->ip_address = strdup(ip);
    } else {
        session->ip_address = NULL;
    }
    
    session->created_at = sqlite3_column_int64(stmt, 5);
    session->last_active = sqlite3_column_int64(stmt, 6);
    
    sqlite3_finalize(stmt);
    return session;
}

// 删除会话
int delete_session(sqlite3 *db, long session_id) {
    sqlite3_stmt *stmt = NULL;
    const char *sql = "DELETE FROM user_session WHERE id = ?;";
    
    int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
        return DB_ERROR;
    }
    
    sqlite3_bind_int64(stmt, 1, session_id);
    
    rc = sqlite3_step(stmt);
    if (rc != SQLITE_DONE) {
        fprintf(stderr, "Delete failed: %s\n", sqlite3_errmsg(db));
        sqlite3_finalize(stmt);
        return DB_ERROR;
    }
    
    int rows_affected = sqlite3_changes(db);
    sqlite3_finalize(stmt);
    
    return (rows_affected > 0) ? DB_SUCCESS : DB_ERROR;
}

// 释放会话内存
void free_session(UserSession *session) {
    if (session) {
        if (session->device_info) free(session->device_info);
        if (session->ip_address) free(session->ip_address);
        free(session);
    }
}

void free_session_array(UserSession **sessions, int count) {
    if (sessions) {
        for (int i = 0; i < count; i++) {
            free_session(sessions[i]);
        }
        free(sessions);
    }
}
